package net.m510.autosurfer.mhbk;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import net.m510.autosurfer.core.DocumentResponseHandler;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class MhbkCsvResponseHandler implements ResponseHandler<File> {
	private static final Logger log = Logger.getLogger(MhbkCsvResponseHandler.class.getName());
	private File file;
	private DocumentResponseHandler dochandler = new DocumentResponseHandler("Shift_JIS");
	private Document doc;
	
	public MhbkCsvResponseHandler(File file) {
		this.file = file;
	}
	
	@Override
	public File handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
		this.doc = dochandler.handleResponse(response);
		List<String> records = new ArrayList<String>();
		log.info("CSV変換中");
		// 明細のテーブル部分取り出し
//		log.finer("doc="+doc.html());
		Element elem = doc.getElementsContainingOwnText("日付").first().parent().parent().parent().parent();
		Elements trs = elem.getElementsByTag("tr");
		for (Element tr : trs) {
			Elements tds = tr.getElementsByTag("td");
			StringBuffer rbuf = new StringBuffer();
			if ( tds.size() == 0 ) continue;
			rbuf.append(tds.get(0).text().trim());	// 日付
			if ( tds.size() > 1 ) {
				rbuf.append("\t").append(tds.get(1).text().replace(",","").replace("円","").trim());	// 出金
				rbuf.append("\t").append(tds.get(2).text().replace(",","").replace("円","").trim());	// 入金
				rbuf.append("\t").append(tds.get(3).text().trim());	// 内容
			}
			records.add(rbuf.toString());
		}
		// ファイルに書き込み
		PrintWriter writer = new PrintWriter(file);
		for (String  s : records) {
			writer.println(s);
		}
		writer.flush();
		writer.close();
		return file;
	}
	
	public Document getDocument() {
		return doc;
	}
}
